package cn.tedu.ivos.base.file;

import cn.tedu.ivos.base.response.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/v1/file")
public class UploadController {
    @PostMapping("/upload")
    public JsonResult uploadFile(MultipartFile file) throws IOException {
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件后缀
//        assert fileName != null;
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //生成一个独特不重复的文件名
//        fileName = System.currentTimeMillis() + suffix;
        fileName = UUID.randomUUID() + suffix;
        //指定路径
        String path = "D:/files" ;
        //方便查找的日期文件路径
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String datePath = sdf.format(new Date());
        File dir = new File(path + "/" + datePath);
        //不存在就创建
        if(!dir.exists()){
            dir.mkdirs();
        }
        //完整路径
        String filePath = path + "/" + datePath + "/" + fileName;
        file.transferTo(new File(filePath));
        //返回成功
        return JsonResult.ok(datePath+ "/" + fileName);

    }
    @PostMapping("/remove")
    public JsonResult removeFile(String imgUrl){
        //指定路径
        String path = "D:/files" ;
        //完整路径
        String filePath = path + "/" + imgUrl;
        File file = new File(filePath);
        if(file.exists()){
            file.delete();
        }
        return JsonResult.ok();
    }
}
